package org.farm2.service.event.utils;


import com.farm2.llm.client.inter.Farm2EmbedClientInter;
import com.farm2.lucene.document.FarmDocument;
import org.farm2.base.domain.FarmUserContext;
import org.farm2.files.domain.ResourceFile;
import org.farm2.files.service.ResourceFileServiceInter;
import org.farm2.files.utils.FileDownloadUtils;
import org.farm2.llm.service.LlmClientServiceInter;
import org.farm2.service.inter.FarmUserServiceInter;
import org.farm2.service.lucene.doc.EmbeddingIndexDocument;
import org.farm2.service.lucene.doc.KnowIndexDocument;
import org.farm2.service.lucene.doc.enums.IndexModelEnum;
import org.farm2.skc.domain.SkcKnow;
import org.farm2.skc.dto.web.IndexTagsDto;
import org.farm2.skc.service.SkcKnowServiceInter;
import org.farm2.tools.files.Farm2FileUtils;
import org.farm2.tools.i18n.I18n;
import org.farm2.tools.web.Farm2HtmlUtils;
import org.farm2.tools.web.domain.TextParagraph;
import org.farm2.wdap.convertor.filemode.impl.SegmentFileMode;
import org.farm2.wdap.convertor.filemode.impl.TextFileMode;
import org.farm2.wdap.service.WdapExtendFileServiceInter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class KnowIndexDocumentBuilder {
    @Autowired
    private ResourceFileServiceInter resourceFileServiceImpl;
    @Autowired
    private FileDownloadUtils fileDownloadUtils;
    @Autowired
    private WdapExtendFileServiceInter wdapExtendFileServiceImpl;
    @Autowired
    private FarmUserServiceInter farmUserService;
    @Autowired
    private SkcKnowServiceInter skcKnowServiceImpl;
    @Autowired
    private LlmClientServiceInter llmClientServiceImpl;

    public KnowIndexDocument getKnowDoc(String knowId) {
        SkcKnow skcKnow = skcKnowServiceImpl.getSkcKnowById(knowId);
        String text = skcKnowServiceImpl.getKnowText(skcKnow);
        FarmUserContext user = farmUserService.getUserByLoginName(skcKnow.getCuserkey());
        IndexTagsDto tags = skcKnowServiceImpl.getKnowIndexTags(skcKnow);
        text = Farm2HtmlUtils.getTextByHtml(text);
        KnowIndexDocument doc = new KnowIndexDocument(knowId, IndexModelEnum.KNOW_DOC, knowId, Farm2HtmlUtils.getTextByHtml(skcKnow.getTitle()), text);
        doc.setUser(user);
        doc.setTag(tags.getKeys(), tags.getTitles());
        doc.setTime(skcKnow.getEtime());
        return doc;
    }

    public KnowIndexDocument getFileDoc(String knowId, String fileId) throws IOException {
        SkcKnow know = skcKnowServiceImpl.getSkcKnowById(knowId);
        IndexTagsDto tags = skcKnowServiceImpl.getKnowIndexTags(know);
        ResourceFile rFile = resourceFileServiceImpl.getResourceFileById(fileId);
        File textFile = new TextFileMode().getFile(rFile, resourceFileServiceImpl);
        String text = Farm2FileUtils.readText(textFile);
        FarmUserContext user = farmUserService.getUserByLoginName(rFile.getCuserkey());
        if (textFile.exists() && knowId != null && !rFile.getExname().equals("html")) {
            KnowIndexDocument doc = new KnowIndexDocument(fileId, IndexModelEnum.FILE, knowId, rFile.getTitle(), text, fileId);
            doc.setUser(user);
            doc.setTime(rFile.getCtime());
            doc.setTag(tags.getKeys(), tags.getTitles());
            return doc;
        } else {
            return null;
        }
    }


    public List<FarmDocument> getVectorDoc(String knowId, String fileId) {
        List<FarmDocument> documents = new ArrayList<>();
        ResourceFile rFile = resourceFileServiceImpl.getResourceFileById(fileId);
        File jsonFile = new SegmentFileMode().getFile(rFile, resourceFileServiceImpl);
        List<TextParagraph> texts = SegmentFileMode.getTextParagraphs(jsonFile);
        SkcKnow know = skcKnowServiceImpl.getSkcKnowById(knowId);
        for (int n = 0; n < texts.size(); n++) {
            try {
                TextParagraph paragraph = texts.get(n);
                String text = paragraph.getText();
                if (n > 0) {
                    text = texts.get(n - 1).getText() + text;
                }
                if (n < (texts.size() - 1)) {
                    text = text + texts.get(n + 1).getText();
                }

                FarmDocument doc = new FarmDocument();
                Farm2EmbedClientInter client = llmClientServiceImpl.getEmbeddingClient();
                if (client == null) {
                    throw new RuntimeException(I18n.msg("无法获取有效的模型向量客户端"));
                }
                float[] vector = client.getEmbedding(text);
                documents.add(new EmbeddingIndexDocument(fileId, knowId, text, know.getTitle() + ":" + paragraph.getSort() + "/" + paragraph.getSize(), paragraph.getSort(), paragraph.getTextLength(), vector).getDoc());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return documents;
    }

}
